﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace TLD_Vision
{
    public class Kernel
    {
        private float[][] kernelData;
        private Boolean isSquare = true;
        private Boolean isNormalized = false;
        private Boolean hasNegativeValues = false;
        private float sum = 0;

        public float[][] KernelData
        {
            get { return kernelData; }
        }

        public Boolean IsNormalized
        {
            get { return isNormalized; }
        }

        public Boolean CanNormalize
        {
            get { return (!hasNegativeValues && !isNormalized); }
        }

        public Kernel(String data)
        {
            Match arrayData = Regex.Match(data, @"\{(.+)\}", RegexOptions.Singleline);
            if (arrayData.Success)
            {
                MatchCollection rows = Regex.Matches(arrayData.Groups[1].Value, @"\{(.+?)\}", RegexOptions.Singleline);
                int numRows = rows.Count;
                kernelData = new float[numRows][];

                for (int rowIndex = 0; rowIndex < numRows; ++rowIndex)
                {
                    String[] rowData = rows[rowIndex].Groups[1].Value.Split(',');
                    int numColumns = rowData.Length;
                    isSquare = isSquare && numColumns == numRows;

                    float[] colData = new float[numColumns];

                    for (int col = 0; col < rowData.Length; ++col)
                    {
                        colData[col] = float.Parse(rowData[col]);
                        sum += colData[col];
                        if (colData[col] < 0)
                        {
                            hasNegativeValues = true;
                        }
                    }

                    kernelData[rowIndex] = colData;
                }
            }
            else
            {
                throw new Exception("No data found.");
            }
        }

        public void Normalize()
        {
            if (hasNegativeValues)
            {
                throw new Exception("Can not normalize a kernel with negative values.");
            }

            for (int row = 0; row < kernelData.Length; row++)
            {
                for (int col = 0; col < kernelData[row].Length; col++)
                {
                    kernelData[row][col] /= sum;
                }
            }

            isNormalized = true;
            sum = 1;
        }

        public override String ToString()
        {
            return "kernel";
        }
    }
}
